
package com.the9tcat.deliverycoming.db;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;

import com.the9tcat.deliverycoming.DeliveryComingActivity;
import com.the9tcat.deliverycoming.MessengerService;
import com.the9tcat.deliverycoming.data.Configure;
import com.the9tcat.deliverycoming.modle.DeliveryDetail;
import com.the9tcat.deliverycoming.modle.DeliveryInfo;
import com.the9tcat.deliverycoming.modle.NotificationCenter;

/**
 * The Class DeliveryDb.
 * 
 * @author ximi
 */
public class DeliveryDb {

    /** The m delivery db adapter. */
    private DeliveryDbAdapter mDeliveryDbAdapter;
    
    private static DeliveryDb mDeliveryDb = null;
    
    private Context mContext;

    /**
     * Instantiates a new delivery db.
     * 
     * @param context the context
     */
    private DeliveryDb(Context context) {
        mDeliveryDbAdapter =  DeliveryDbAdapter.getDatabaseAdapter(context);
        this.mContext = context;
    }
    
    public static synchronized DeliveryDb getDb(Context context){
        if(mDeliveryDb == null){
            mDeliveryDb = new DeliveryDb(context);
        }
        return mDeliveryDb;
    }

//    /**
//     * Open.
//     */
//    public void open() {
//    	mDeliveryDbAdapter = mDeliveryDbAdapter.open();
//    }

    /**
     * Close.
     */
    public void close() {
    	if(!DeliveryComingActivity.app_running&&!MessengerService.service_running){
    		try{
        		mDeliveryDbAdapter.close();
        		mDeliveryDb = null;
        	}catch(Exception e){
        		
        	} 
    	}
    }

    /**
     * Adds the.
     * 
     * @param delivery the delivery
     */
    public synchronized long add(DeliveryInfo delivery) {
        long trackId = mDeliveryDbAdapter
                .addToTrackList(delivery.getExpressNu(), delivery.getCompanyId(),
                                delivery.getExpComName(), delivery
                                        .getLatestTime(), delivery
                                        .getLatestStatus(), delivery.getColor(),
                                delivery.getName(), (delivery.isSigned() ? 1 : 0));
        ArrayList<DeliveryDetail> details = delivery.getDetail();
        int size = details.size();
        DeliveryDetail dd;
        for(int i=size-1;i>=0;i--){
        	dd = details.get(i);
        	if(dd.getId()<=0){
        		dd.setId(mDeliveryDbAdapter.addToDetails((int) trackId, dd
                        .getTime(), dd.getStatus()));
        	}
        }
        return trackId;
        
    }


    /**
     * Update.
     * 
     * @param DeliveryInfo 首先查找detail list里面是否有ID小于等于0的对象，如果有认为有更新。
     * 					        完成新的数据插入后同时会更新DeviceInfo里面的latest字段，
     * 					   latest字段请自己设定好。
     * @return true, 如果有更新返回true，否则不返回
     */
    public synchronized boolean update(DeliveryInfo d_info) {
        boolean needUpdate = false;
        java.util.List<DeliveryDetail> tmp_details = d_info.getDetail();
        int size = tmp_details.size();
        DeliveryDetail dd;
        for(int i=size-1;i>=0;i--){
        	dd = tmp_details.get(i);
        	if(dd.getId()<=0){
        		needUpdate = true;
        		//插入成功了，把主键ID写进去
        		dd.setId(mDeliveryDbAdapter.addToDetails(d_info.getId(),
        				dd.getTime(),
        				dd.getStatus()));
        	}
        }
        if(needUpdate){
        	mDeliveryDbAdapter.updateDeliveryStatus(d_info.getId(), d_info.getLatestTime(), d_info.getLatestStatus());
        }
        return needUpdate;
    }

    public synchronized boolean updateSigned(int trackId, int signed) {
        return mDeliveryDbAdapter.updateDeliverySigned(trackId, signed);
    }

    /**
     * Delete.
     * 
     * @param number the number
     * @param company the company
     */
    public synchronized void delete(int trackId) {
        mDeliveryDbAdapter.deleteFromDetails(trackId);
        mDeliveryDbAdapter.deleteFromTrackList(trackId);
        NotificationCenter.getNotificationCenter(mContext).removeNotification(trackId);
    }

    /**
     * 
     * @param mode Configure.MODE_UNSIGNED_TRACKLIST or Configure.MODE_UNSIGNED_TRACKLIST
     * @return
     */
    
    public synchronized ArrayList<DeliveryInfo> getDeliveryInTrack(int mode) {
        ArrayList<DeliveryInfo> deliveryList = new ArrayList<DeliveryInfo>();
        final Cursor cursor = mDeliveryDbAdapter.fetchAllTrackListItem(mode);
        if (cursor.getCount() == 0) {
            cursor.close();
            return deliveryList;
        }
        cursor.moveToFirst();
        do {
            DeliveryInfo deliveryItem = new DeliveryInfo();
            deliveryItem.setId(cursor.getInt(cursor
                    .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_ROWID)));
            deliveryItem.setName(cursor.getString(cursor
                    .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_NAME)));
            deliveryItem.setExpressNu(cursor.getString(cursor
                    .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_EXP_NU)));
            deliveryItem.setColor(cursor.getInt(cursor
                    .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_COLOR)));
            deliveryItem.setCompanyId(cursor.getString(cursor
                    .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_COM_ID)));
            deliveryItem.setExpComName(cursor.getString(cursor
                    .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_COM_NAME)));
            deliveryItem.setLatestTime(cursor.getString(cursor
                    .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_LATESTTIME)));
            deliveryItem.setLatestStatus(cursor.getString(cursor
                    .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_LATESTSTATUS)));
            deliveryItem.setSigned(cursor.getInt(cursor
                    .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_SIGNED)) == 1);
            deliveryItem.setDetail(getDetails(deliveryItem.getId()));
            deliveryList.add(deliveryItem);

        } while (cursor.moveToNext());
        cursor.close();
        return deliveryList;

    }


    public synchronized DeliveryInfo getDelivery(int trackId) {
        DeliveryInfo delivery = new DeliveryInfo();
        delivery.setId(trackId);
        final Cursor cursor = mDeliveryDbAdapter.fetchTrackListItem(trackId);
        if (cursor.getCount() == 0) {
            cursor.close();
            return null;
        }
        cursor.moveToFirst();

        delivery.setName(cursor.getString(cursor
                .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_NAME)));
        delivery.setExpressNu(cursor.getString(cursor
                .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_EXP_NU)));
        delivery.setColor(cursor.getInt(cursor
                .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_COLOR)));
        delivery.setCompanyId(cursor.getString(cursor
                .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_COM_ID)));
        delivery.setExpComName(cursor.getString(cursor
                .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_COM_NAME)));
        delivery.setLatestTime(cursor.getString(cursor
                .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_LATESTTIME)));
        delivery.setLatestStatus(cursor.getString(cursor
                .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_LATESTSTATUS)));
        delivery.setSigned(cursor.getInt(cursor
                .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_SIGNED)) == 1);
        delivery.setDetail(getDetails(trackId));
        cursor.close();
        return delivery;
    }

    /**
     * Gets the details.
     * 
     * @param number the number
     * @param company the company
     * @return the details
     */
    public ArrayList<DeliveryDetail> getDetails(int trackId) {
        ArrayList<DeliveryDetail> Details = new ArrayList<DeliveryDetail>();
        final Cursor cursor = mDeliveryDbAdapter.fetchDetails(trackId);
        if (cursor.getCount() == 0) {
            cursor.close();
            return null;
        }
        cursor.moveToFirst();
        do {
            DeliveryDetail deliveryDetail = new DeliveryDetail();
            deliveryDetail.setId(cursor.getInt(cursor
                    .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_ROWID)));
            deliveryDetail.setTrackId(cursor.getInt(cursor
                    .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_TRACK_ID)));
            deliveryDetail.setTime(cursor.getString(cursor
                    .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_TIME)));
            deliveryDetail.setStatus(cursor.getString(cursor
                    .getColumnIndexOrThrow(DeliveryDbAdapter.KEY_STATUS)));
            Details.add(deliveryDetail);

        } while (cursor.moveToNext());
        cursor.close();
        return Details;
    }

    /**
     * Gets the latest update time.
     * 
     * @param trackId the track id
     * @return the latest update time
     */
    public synchronized String getLatestUpdateTime(int trackId) {
        return mDeliveryDbAdapter.fetchLatestUpdateTime(trackId);
    }

    public synchronized Cursor getTrackCursor() {
        return mDeliveryDbAdapter.fetchAllTrackListItem(Configure.MODE_ALL_TRACKLIST);
    }
    
    public boolean updateDeliveryInfo(DeliveryInfo info,long trackId){
    	//mDeliveryDbAdapter.open();
    	mDeliveryDbAdapter.updateDeliveryInfo(info,trackId);
    	//mDeliveryDbAdapter.close();
    	return true;
    }

    public boolean isTrackExist(String com, String nu) {
    	return mDeliveryDbAdapter.isTrackExist(com, nu);
    }
}
